//
//  ocean.m
//  ltw
//
//  Created by kato on 2/19/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ocean.h"

@implementation ocean

int a = 0;
@synthesize tilemap = _tilemap;
@synthesize background = _background;
@synthesize player = _player;

-(id) init
{
    if( (self=[super init] )) {
        
        self.tilemap = [CCTMXTiledMap tiledMapWithTMXFile:@"ocean.tmx"];
        self.background = [_tilemap layerNamed:@"Background"];
        [self addChild:_tilemap z:-1];
        //self.position = ccp(0,-1280);
        
        CCTMXObjectGroup *objects = [_tilemap objectGroupNamed:@"Objects"];
        
        NSMutableDictionary *spawnPoint = [objects objectNamed:@"SpawnPoint"];
        //[self schedule:@selector(update:) interval:0.8];
        
        int x = [[spawnPoint valueForKey:@"x"] intValue];
        int y = [[spawnPoint valueForKey:@"y"] intValue];     
        
        self.player = [CCSprite spriteWithFile:@"frog.png"];
        _player.position = ccp(x,y);
        [self addChild:_player];
        
        
        [self setViewpointCenter:_player.position];
    
    }
    return self;
}

-(void)update:(id)sender
{

    if (a==0) {
        self.position = ccp (-8,-1280);
        a=1;
    } else {
        self.position = ccp (0,-1280);
        a=0;
    }
    
}

-(void)setViewpointCenter:(CGPoint) position{
    CGSize winSize = [[CCDirector sharedDirector] winSize];
    int x = MAX(position.x, winSize.width /2);
    int y = MAX(position.y, winSize.height /2);
    x = MIN(x, (_tilemap.mapSize.width * _tilemap.tileSize.width)-winSize.width /2);
    y = MIN(y, (_tilemap.mapSize.height * _tilemap.tileSize.height) 
            - winSize.height/2);
    CGPoint actualPosition = ccp(x,y);
    
    CGPoint centerOfView = ccp(winSize.width/2,winSize.height/2);
    CGPoint viewPoint = ccpSub(centerOfView, actualPosition);
    self.position = viewPoint;
    
}

-(void)dealloc{
    self.tilemap = nil;
    self.background = nil;
    self.player = nil;
    [super dealloc];
}

@end
